package cn.lyj.study.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Random;


/**
 * @author lyj
 * @Date 2021-08-17
 */
public class UploadUtils {
    public static String upload(MultipartFile file , HttpServletRequest request){
        System.out.println(file);   //  打印文件名
        System.out.println(file.getOriginalFilename());
        //获取服务器上传的地址
        String realPath = request.getServletContext().getRealPath("/upload");
        System.out.println(realPath);
        //对上传的文件名进行处理
        long tl = new Date().getTime();
        //对上传的文件名称进行处理
        long lt=new Date().getTime();  //系统当前时间的毫秒值
        String newName=lt+new Random().nextInt()+""+file.getOriginalFilename();

        //文件上传
        File baseFile=new File(realPath);
        if(!baseFile.exists()){
            baseFile.mkdir(); //新建上传目录
        }

        File to=new File(realPath+"/"+newName);
        try {
            file.transferTo(to);   //文件另存为
        } catch (IOException e) {
            e.printStackTrace();
            return "error";
        }



        return "http://localhost/proSSM/upload/"+newName ;




    }
}
